package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.common.persistence.model.ProjectAuthenPoints;
import com.stylefeng.guns.common.persistence.model.QualityGradeRule;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.common.persistence.model.TrainerExcellentPoints;
import com.stylefeng.guns.modular.train.service.ITrainerExcellentPointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 优秀兼职培训师控制器
 *
 * @author fengshuonan
 * @Date 2018-01-24 21:30:59
 */
@Controller
@RequestMapping("/trainerExcellentPoints")
public class TrainerExcellentPointsController extends BaseController {

    private String PREFIX = "/train/trainerExcellentPoints/";

    @Autowired
    private ITrainerExcellentPointsService trainerExcellentPointsService;
    @Autowired
    private IDictService dictService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;

    @Autowired
    private IEmployeeService employeeService;

    private static List<TrainerExcellentPoints> REPEAT = new ArrayList<>();


    /**
     * 跳转到trainerExcellentnPoints首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "trainerExcellentPoints.html";
    }

    /**
     * 跳转到添加trainerExcellentnPoints
     */
    @RequestMapping("/trainerExcellentPoints_add")
    public String trainerExcellentPointsAdd(Model model) {
        model.addAttribute("au_majors", dictService.getByPCode("au_major"));
        model.addAttribute("authens", qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_EXCELLENT));
        return PREFIX + "trainerExcellentPoints_add.html";
    }

    /**
     * 跳转到修改trainerExcellentnPoints
     */
    @RequestMapping("/trainerExcellentPoints_update/{trainerExcellentPointsId}")
    public String trainerExcellentPointsUpdate(@PathVariable String trainerExcellentPointsId, Model model) {
        TrainerExcellentPoints trainerExcellentPoints = trainerExcellentPointsService.selectById(trainerExcellentPointsId);
        model.addAttribute("item",trainerExcellentPoints);
        model.addAttribute("au_majors", dictService.getByPCode("au_major"));
        model.addAttribute("authens", qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_EXCELLENT));
        LogObjectHolder.me().set(trainerExcellentPoints);
        return PREFIX + "trainerExcellentPoints_edit.html";
    }

    /**
     * 获取trainerExcellentnPoints列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            List<TrainerExcellentPoints> trainerExcellentPointss = trainerExcellentPointsService.selectList(null);
            trainerExcellentPointss.forEach(t->{
                if(t.getIssuingDate() != null){
                    t.setStrIssuingDate(Const.df.format(t.getIssuingDate()));
                }
            });
            return trainerExcellentPointss;
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<TrainerExcellentPoints> list = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<TrainerExcellentPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }

            list= trainerExcellentPointsService.selectList(nwWrapper);
        }
        list.forEach(t->{
            if(t.getIssuingDate() != null){
                t.setStrIssuingDate(Const.df.format(t.getIssuingDate()));
            }
        });
        return list;
    }
    /**
     * 新增trainerExcellentnPoints
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(TrainerExcellentPoints trainerExcellentPoints) {
        trainerExcellentPointsService.insert(trainerExcellentPoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody TrainerExcellentPoints[] repeatData) {
        List<TrainerExcellentPoints> trainerExcellentPointss = Arrays.asList(repeatData);
        Date now = new Date();
        List<QualityGradeRule> qualityGradeRules=qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_EXCELLENT);
        trainerExcellentPointss.forEach(trainerExcellentPoints -> {
            trainerExcellentPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
            trainerExcellentPoints.setCreateDate(now);
            qualityGradeRules.forEach(item->{
                if(item.getGrade().equals(trainerExcellentPoints.getAuthen())){
                    trainerExcellentPoints.setAuthenCode(item.getGradeCode());
                    trainerExcellentPoints.setIntegral(item.getIntegral());
                }
            });
        });
        trainerExcellentPointsService.insertBatch(trainerExcellentPointss);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除trainerExcellentnPoints
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String trainerExcellentPointsId) {
        if(trainerExcellentPointsId.contains(",")){
            List<String> ids = Arrays.asList(trainerExcellentPointsId.split(","));
            trainerExcellentPointsService.deleteBatchIds(ids);
        }else{
            trainerExcellentPointsService.deleteById(trainerExcellentPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改trainerExcellentnPoints
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(TrainerExcellentPoints trainerExcellentPoints) {
        trainerExcellentPointsService.updateById(trainerExcellentPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * trainerExcellentnPoints详情
     */
    @RequestMapping(value = "/detail/{trainerExcellentPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("trainerExcellentPointsId") String trainerExcellentPointsId) {
        return trainerExcellentPointsService.selectById(trainerExcellentPointsId);
    }


    /**
     * 跳转到导入trainerExcellentnPoints
     */
    @RequestMapping("/trainerExcellentPoints_import")
    public String trainerExcellentPointsImport() {
        return PREFIX + "trainerExcellentPoints_import.html";
    }

    /**
     * 导入trainerExcellentnPoints
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);
        int count =2;

        try {
            List<TrainerExcellentPoints> trainerExcellentPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), TrainerExcellentPoints.class, params);
            Date now = new Date();
            List<QualityGradeRule> qualityGradeRules=qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_EXCELLENT);

            Map<String, String> nameAndCode = employeeService.getNameAndCode();
            List<TrainerExcellentPoints> noRepeat = new ArrayList<>();
            List<TrainerExcellentPoints> hasNameList = new ArrayList<>();

            for (TrainerExcellentPoints trainerExcellentPoints : trainerExcellentPointss) {
                trainerExcellentPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
                trainerExcellentPoints.setCreateDate(now);

                if(StringUtils.isEmpty(trainerExcellentPoints.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(trainerExcellentPoints.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(trainerExcellentPoints.getEmpName()).contains(",")) {
                            //有重名情况
                            trainerExcellentPoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(trainerExcellentPoints);
                        } else {
                            //无重名、正常插入
                            trainerExcellentPoints.setEmpCode(nameAndCode.get(trainerExcellentPoints.getEmpName()));

                            qualityGradeRules.forEach(item->{
                                if(item.getGrade().equals(trainerExcellentPoints.getAuthen())){
                                    trainerExcellentPoints.setAuthenCode(item.getGradeCode());
                                    trainerExcellentPoints.setIntegral(item.getIntegral());
                                }
                            });

                            noRepeat.add(trainerExcellentPoints);
                        }
                    } else {
                        throw new Exception("姓名为 " + trainerExcellentPoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    qualityGradeRules.forEach(item->{
                        if(item.getGrade().equals(trainerExcellentPoints.getAuthen())){
                            trainerExcellentPoints.setAuthenCode(item.getGradeCode());
                            trainerExcellentPoints.setIntegral(item.getIntegral());
                        }
                    });

                    hasNameList.add(trainerExcellentPoints);
                }

                count++;
            }
            //不重复，先插入
            if(noRepeat.size() > 0){
                trainerExcellentPointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                trainerExcellentPointsService.insertBatch(hasNameList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<TrainerExcellentPoints> trainerExcellentPoints= trainerExcellentPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("优秀兼职培训师积分统计表", "优秀兼职培训师积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TrainerExcellentPoints.class, trainerExcellentPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="优秀兼职培训师积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
